import logging
from datetime import datetime
import re
from typing import Dict, Optional, Union

class PaperValidator:
    """论文数据验证器"""
    
    def __init__(self, min_content_length: int = 2000):
        self.logger = logging.getLogger(__name__)
        self.min_content_length = min_content_length
        self.min_year = 1990
        self.max_year = datetime.now().year
        
    def is_valid_paper(self, paper: Dict) -> bool:
        """验证论文数据的有效性"""
        try:
            if not paper:
                return False

            # 检查必需字段
            required_fields = ['title', 'content', 'venue', 'year']
            if not all(paper.get(field) for field in required_fields):
                self.logger.debug(f"缺少必需字段: {[f for f in required_fields if not paper.get(f)]}")
                return False
            
            # 内容长度检查
            if len(str(paper.get('content', '')).strip()) < self.min_content_length:
                self.logger.debug("内容长度不足")
                return False
            
            # 标题检查
            if len(str(paper.get('title', '')).strip()) < 10:
                self.logger.debug("标题长度不足")
                return False
            
            # 年份检查
            year = paper.get('year')
            if not isinstance(year, (int, str)) or not self._check_year(year):
                self.logger.debug(f"无效年份: {year}")
                return False
            
            return True
            
        except Exception as e:
            self.logger.error(f"论文验证失败: {str(e)}")
            return False
    
    def _check_required_fields(self, paper: Dict) -> bool:
        return all(paper.get(field) for field in ['title', 'content', 'year'])
    
    def _check_year(self, year: Optional[str]) -> bool:
        try:
            year_int = self.validate_year(year)
            return self.min_year <= year_int <= self.max_year
        except:
            return False
            
    def _check_content_length(self, content: str) -> bool:
        return len(content.strip()) >= self.min_content_length
        
    def _check_title_format(self, title: str) -> bool:
        return bool(re.match(r'^[\w\s\-:]{10,200}$', title))
        
    def validate_year(self, year: Union[str, int]) -> Optional[int]:
        """验证并规范化年份"""
        try:
            if isinstance(year, str):
                # 尝试从字符串中提取年份
                year = int(''.join(filter(str.isdigit, year)))
            elif isinstance(year, int):
                year = int(year)
            else:
                return None

            # 验证年份范围
            if self.min_year <= year <= self.max_year:
                return year
            return self.max_year
            
        except (ValueError, TypeError):
            return self.max_year
